package com.lingxu.base.system.fileManage.controller;

import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.exception.BussException;
import com.lingxu.base.common.util.FileUtils;
import com.lingxu.base.common.util.HandlerUtil;
import com.lingxu.base.common.util.ToolUtil;
import com.lingxu.base.system.fileManage.entity.SysFileInfo;
import com.lingxu.base.system.fileManage.entity.SysFileInfoVo;
import com.lingxu.base.system.fileManage.service.SysFileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Api(tags="文件上传")
@RestController
@RequestMapping(value = "/sys/file")
public class SysFileInfoController {

    @Autowired
    private SysFileInfoService sysFileInfoService;


    @Value(value = "${uploadUrl}")
    private String uploadpath;

    @ApiOperation(value="文件上传-文件上传(只是文件上传到指定位置未保存入库)", notes="文件上传-只是文件上传到指定位置未保存入库")
    @PostMapping(value = "/upload")
    public Result upload(HttpServletRequest request, HttpServletResponse response){
        Result<SysFileInfo> result = new Result<>();
        String createby = request.getParameter("createby");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
//		 上传至本地服务器
        String savePath = this.uploadLocal(file);
        if(StringUtils.isEmpty(savePath)){
            result.setMessage("上传失败！");
            result.setSuccess(false);
            return result;
        }
        try {
            //生成文件的唯一id
            String fileId = UUID.randomUUID().toString();
            //获取文件后缀
            String fileSuffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
            //获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            //保存文件信息
            SysFileInfo fileInfo = new SysFileInfo();
            fileInfo.setId(fileId);
            fileInfo.setCreatetime(new Date());
            fileInfo.setCreateby(createby);
            fileInfo.setFileName(originalFilename);
            fileInfo.setFileSuffix(fileSuffix);
            fileInfo.setFilePath(savePath);
            fileInfo.setFileSize(HandlerUtil.formatFileSize(file.getSize()));
            fileInfo.setIsdel("0");
//            sysFileInfoService.save(fileInfo);

            result.setMessage("上传成功！");
            result.setResult(fileInfo);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setMessage("上传文件错误！"+ e.getMessage());
            result.setSuccess(false);
            throw new BussException("上传文件错误！"+ e.getMessage());
        }
        return result;
    }


    /**
     * 本地文件上传
     * @param mf 文件
     * @return
     */
    private String uploadLocal(MultipartFile mf){
        try {
            String ctxPath = uploadpath + "/infos/";
            String fileName = null;
            File file = new File(ctxPath);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            if(orgName.lastIndexOf(".")<0){
                fileName=orgName+ "_" + System.currentTimeMillis();
            }else{
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            }
            String savePath = ctxPath + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            return "/ptmh/res/" + fileName;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    @ApiOperation(value="附件表-更新附件", notes="附件表-更新附件")
    @PostMapping(value = "/updateByRecordID")
    public Result<?> updateByRecordID(@RequestBody SysFileInfoVo sysFileInfo) {
//		new是最终操作的附件总合
        List<SysFileInfo> newFileInfos = sysFileInfo.getNewFileInfos();
        //		old是操作之前的附件总合
        List<SysFileInfo> oldFileInfos = sysFileInfo.getOldFileInfos();
        List<SysFileInfo> addFileList = new ArrayList<>();
        List<String> delFileIds = new ArrayList<>();
//		先用旧附件和新附件对比，找不到的就是需要删除的
        for (int i = 0; i < oldFileInfos.size(); i++) {
            SysFileInfo oldFileInfo = oldFileInfos.get(i);
            boolean isExist = false;
            for (int j = 0; j < newFileInfos.size(); j++) {
                SysFileInfo newFileInfo = newFileInfos.get(j);
                if (oldFileInfo.getId().equals(newFileInfo.getId())){
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                delFileIds.add(oldFileInfo.getId());
                FileUtils.delete(oldFileInfo.getFilePath());
            }
        }
//		再用新附件和旧附件对比，如果找不到就是新增了
        for (int k = 0; k < newFileInfos.size(); k++) {
            SysFileInfo newFileInfo1 = newFileInfos.get(k);
            boolean isExist = false;
            for (int l = 0; l < oldFileInfos.size(); l++) {
                SysFileInfo oldFileInfo1 = oldFileInfos.get(l);
                if (newFileInfo1.getId().equals(oldFileInfo1.getId())) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                addFileList.add(newFileInfo1);
            }

        }

        if (delFileIds.size() > 0) {
            sysFileInfoService.removeByIds(delFileIds);
        }
        if (addFileList.size() > 0) {
            sysFileInfoService.saveBatch(addFileList);
        }
        return Result.ok("修改成功");
    }

    @ApiOperation(value="附件表-添加", notes="附件表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody List<SysFileInfo> fileInfos) {
        sysFileInfoService.saveBatch(fileInfos);
        return Result.ok("添加成功！");
    }


}
